<?php
require_once ROOT.'/app/task.php';

class search extends page{
	
	private $pageSize = 10;
	
	private $top_type = array();
	
	function __construct(){
		parent::__construct();
		
		$this->top_type = array(
			'1' => '奇幻·玄幻',
			'2' => '武侠·仙侠',
			'3' => '历史·军事',
			'4' => '都市·娱乐',
			'5' => '竞技·同人',	
			'6' => '科幻·游戏',
			'7' => '悬疑·灵异',
			'8' => '女生·言情',
		);
	}
	
	function searchByTerm(){
		$term = trim($this->req['t']);
		$cate = intval(trim($this->req['c']));
		
		$return = array();
		if(!$term){
			$return['message'] = '无关键字';
			$return['status'] = $this->f_status;
			G::toClient($return);
		}
		
		$sql = "SELECT id, title, summary, author, cateId, file, last FROM book WHERE status = 1 AND title like '%{$term}%' or author like '%{$term}%'";
		if($cate){
			$sql .= " AND cateId = '{$cate}' ";
		}		
		$memKey = md5($sql);
		$result = $this->memGet($memKey);	// cache
		if(!$result){
			$result = $this->db->query($sql)->fetchAll();
			
			if(!$result){	//如果没有搜到建立系统任务
				$taskClass = new task();
				$taskClass->create($term);
			}else{
				$this->memSet($memKey, $result);	// cache
			}
		}
		
		$return['list'] = $result;
		$return['status'] = $this->s_status;
		G::toClient($return);
	}
	
	function top(){
		$cate = intval($this->req['c']);
		
		$sql = "SELECT t2.id, t2.title, t2.summary, t2.author, t2.cateId, t2.file, t2.last FROM top t1 LEFT JOIN book t2 ON t1.bookid=t2.id WHERE t1.type='{$cate}' ORDER BY t1.order";
		$memKey = md5($sql);
		$result = $this->memGet($memKey);	// cache
		if(!$result){
			$result = $this->db->query($sql)->fetchAll();
			$this->memSet($memKey, $result);	// cache
		}
		
		if(!$cate){
			$return['cateList'] = $this->top_type;	
		}
		$return['list'] = $result;
		$return['status'] = $this->s_status;
		G::toClient($return);
	}
	
	function getCateList(){
		
		$cateSql = "select cateId, cateName from cate";
		$memKey = md5($cateSql);
		$result = $this->memGet($memKey);	// cache
		if(!$result){
			$result = $this->db->query($cateSql)->fetchAll();
			$this->memSet($memKey, $result);	// cache
		}
		
		$json['list'] = $result;
		$json['status'] = $this->s_status;
		G::toClient($json);
	}

	function getListByCate(){
		$cate = intval($this->req['cate']);
		$index = intval($this->req['i']);

		$sql = "SELECT id, title, summary, author, cateId, file, last from book where cateId='{$cate}' order by update_time desc limit {$index}, 20";
		$memKey = md5($sql);
                $result = $this->memGet($memKey);       // cache
                if(!$result){
                        $result = $this->db->query($sql)->fetchAll();
                        $this->memSet($memKey, $result);        // cache
                }
		$return['list'] = $result;
                $return['status'] = $this->s_status;
                G::toClient($return);
	}
}
